package com.wildlife.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wildlife.springboot.common.Result;
import com.wildlife.springboot.entity.BirdFeature;
import com.wildlife.springboot.entity.LizardFeature;
import com.wildlife.springboot.mapper.service.ImageUploadService;
import com.wildlife.springboot.service.ILizardFeatureService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/lizardFeature")
public class LizardFeatureController {

    @Resource
    private ILizardFeatureService lizardFeatureService;

    @Resource
    private ImageUploadService imageUploadService;

    //新增和修改
    @PostMapping
    public Result save(@RequestBody LizardFeature lizardFeature){
        //新增或更新
        return Result.success(lizardFeatureService.saveOrUpdate(lizardFeature));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(lizardFeatureService.removeById(id));
    }

    @PostMapping ("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(lizardFeatureService.removeByIds(ids));
    }

    @GetMapping
    public Result findAll() {
        return Result.success(lizardFeatureService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(lizardFeatureService.getById(id));
    }

    @GetMapping("/chineseName/{chineseName}")
    public Result findOne(@PathVariable String chineseName) {
        QueryWrapper<LizardFeature> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chinese_name", chineseName);
        return Result.success(lizardFeatureService.getOne(queryWrapper));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String chineseName
    ) {
        QueryWrapper<LizardFeature> queryWrapper = new QueryWrapper<>();
        if (!"".equals(chineseName)) {
            queryWrapper.like("chinese_name", chineseName);
        }
//        if (!"".equals(email)) {
//            queryWrapper.like("email", email);
//        }
//        if (!"".equals(address)) {
//            queryWrapper.like("address", address);
//        }
        return Result.success(lizardFeatureService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    // 导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<LizardFeature> list = lizardFeatureService.list();
        // 通过工具类创建writer 写出到磁盘路径

        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("outline", "目");
        writer.addHeaderAlias("section", "科");
        writer.addHeaderAlias("genus", "属");
        writer.addHeaderAlias("chines_name", "种中文名");
        writer.addHeaderAlias("latin_name", "种拉丁名");
        writer.addHeaderAlias("describe_year", "描述年份");
        writer.addHeaderAlias("chinese_threat", "中国受威胁等级");
        writer.addHeaderAlias("iucn", "全球受威胁等级");
        writer.addHeaderAlias("chinese_endemic_species", "是否中国特有种");
        writer.addHeaderAlias("island_endemic_species", "是否岛屿特有种");
        writer.addHeaderAlias("average_length", "平均体长(mm)");
        writer.addHeaderAlias("average_weight", "平均体重(g)");
        writer.addHeaderAlias("diet", "食性");
        writer.addHeaderAlias("egg_count", "窝卵数");
        writer.addHeaderAlias("reproductive_mode", "繁殖模式");
        writer.addHeaderAlias("limb_development", "四肢发育");
        writer.addHeaderAlias("activity_time", "活动时间");
        writer.addHeaderAlias("habitat", "栖息生境");
        writer.addHeaderAlias("habitat_type", "栖息地类型");
        writer.addHeaderAlias("habitat_width", "栖息地宽度");
        writer.addHeaderAlias("altitude_range", "海拔分布范围(m)");
        writer.addHeaderAlias("distribution_range", "地理分布范围(km²)");
        writer.addHeaderAlias("animal_geography", "动物地理界");
        writer.addHeaderAlias("area", "分布省份");

        writer.write(list, true);

        // 设置浏览器相应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("蜥蜴类特征表", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    // 导入接口
    // reader.addHeaderAlias(): 忽略表头的中文
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("ID", "id");
        reader.addHeaderAlias("目", "outline");
        reader.addHeaderAlias("科", "section");
        reader.addHeaderAlias("属", "genus");
        reader.addHeaderAlias("种中文名", "chinese_name");
        reader.addHeaderAlias("种拉丁名", "latin_name");
        reader.addHeaderAlias("描述年份", "describe_year");
        reader.addHeaderAlias("中国受威胁等级", "chinese_threat");
        reader.addHeaderAlias("全球受威胁等级", "iucn");
        reader.addHeaderAlias("是否中国特有种", "chinese_endemic_species");
        reader.addHeaderAlias("是否岛屿特有种", "island_endemic_species");
        reader.addHeaderAlias("平均体长(mm)", "average_length");
        reader.addHeaderAlias("平均体重(g)", "average_weight");
        reader.addHeaderAlias("食性", "diet");
        reader.addHeaderAlias("窝卵数", "egg_count");
        reader.addHeaderAlias("繁殖模式", "reproductive_mode");
        reader.addHeaderAlias("四肢发育", "limb_development");
        reader.addHeaderAlias("活动时间", "activity_time");
        reader.addHeaderAlias("栖息生境", "habitat");
        reader.addHeaderAlias("栖息地类型", "habitat_type");
        reader.addHeaderAlias("栖息地宽度", "habitat_width");
        reader.addHeaderAlias("海拔分布范围(m)", "altitude_range");
        reader.addHeaderAlias("地理分布范围(km²)", "distribution_range");
        reader.addHeaderAlias("动物地理界", "animal_geography");
        reader.addHeaderAlias("分布省份", "area");
        List<LizardFeature> list = reader.readAll(LizardFeature.class);
        lizardFeatureService.saveBatch(list);
        return true;
    }

    // 上传图片接口
    @PostMapping("/upload")
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String url = imageUploadService.uploadImage(file);
            // 返回相对路径而不是完整的本地文件路径
            return Result.success(url);
        } catch (Exception e) {
            return Result.fail("上传失败");
        }
    }
}
